#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
using LL = long long;
int T;
LL a, m;

LL gcd(LL a, LL m)
{
    return m ? gcd(m, a % m) : a;
}

LL qmi(LL a)
{
    LL res = a;
    for(LL i = 2; i <= a / i; ++i)
    {
        if(a % i == 0)
        {
            while(a % i == 0) a /= i;
            res = res / i * (i - 1);
        }
    }
    if(a > 1) res = res / a * (a - 1);
    return res;
}

int main()
{
    cin >> T;
    while(T--)
    {
        cin >> a >> m;
        LL d = gcd(a, m);
        // cout << d << endl;
        cout << qmi(m / d) << endl;
    }
    return 0;
}